﻿using System;
using System.Data;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using System.Collections;

namespace UpFile
{
    public partial class Download : Form
    {
        #region 变量
        FTPClient ftpdown = null;
        FTPClient ftpup = null;
        string fileName;
        string previousFileName;
        string strGIud;
        string strsuffix;
        static string newfileName;
        string filetitle;
        string URLVideoPhoto;
        string newVideoImage;
        int userid;
        string username;
        int branchid;
        int branchidfrom;
        string NASIP;
        int flag;//判断该上传文件类型 0表示图片文件 1表示视频文件
        bool ishead;//判断是否是总店在进行上传操作
        string URL = "";
        string itemsToDown;
        string NASusername = System.Configuration.ConfigurationSettings.AppSettings["LocalUserName"];//NAS用户名
        string NASpassword = System.Configuration.ConfigurationSettings.AppSettings["LocalPassword"];//NAS密码
        string firstURL = System.Configuration.ConfigurationSettings.AppSettings["URL"];
        string ImageURL = System.Configuration.ConfigurationSettings.AppSettings["ImageURL"];//图片存储二级地址
        string VideoURL = System.Configuration.ConfigurationSettings.AppSettings["VideoURL"];//视频存储二级地址
        string HeadNASIP = System.Configuration.ConfigurationSettings.AppSettings["HeadNASIP"];//总店NAS服务器IP地址
        string HeadnasUserName = System.Configuration.ConfigurationSettings.AppSettings["HeadUserName"];//总店NAS用户名
        string HeadnasPassword = System.Configuration.ConfigurationSettings.AppSettings["HeadPassword"];//总店NAS密码
        static DataTable filelist;
        #endregion

        #region 构造函数
        public Download()
        {

            InitializeComponent();
            UpImage.UpFileSoapClient server = new UpImage.UpFileSoapClient();
            filelist = server.GetFileDownList(branchid).Tables[0];
            UserPageToolBind(filelist);
            DataCombox();
            DataBind(filelist);
        }

        //构造函数重载
        public Download(int user_id, string user_name, int branch_id, string NAS_IP, bool is_head)
        {
            try
            {
                userid = user_id;
                username = user_name;
                branchid = branch_id;
                NASIP = NAS_IP;
                InitializeComponent();
                this.dti_startTimeFrom.Value = DateTime.Now.AddMonths(-1);
                this.dti_startTimeTo.Value = DateTime.Now;
                UpImage.UpFileSoapClient server = new UpImage.UpFileSoapClient();
                filelist = server.GetFileDownList(branchid).Tables[0];
                UserPageToolBind(filelist);
                DataCombox();
                DataBind(filelist);
                this.cmb_star.SelectedIndex =0;
                this.cmb_first.SelectedIndex = 0;
                string[] arrTitle = new string[filelist.Rows.Count];
                string[] arrUser = new string[filelist.Rows.Count];
                string[] arrBranch = new string[filelist.Rows.Count];
                for (int i = 0; i < arrTitle.Length; i++)
                {
                    arrTitle[i] = filelist.Rows[i][3].ToString();
                    arrUser[i] = filelist.Rows[i][5].ToString();
                    arrBranch[i] = filelist.Rows[i][7].ToString();
                }
                this.txt_branch.AutoCompleteCustomSource.AddRange(arrBranch);
                this.txt_title.AutoCompleteCustomSource.AddRange(arrTitle);
                this.txb_user.AutoCompleteCustomSource.AddRange(arrUser);
            }
            catch (Exception)
            {
                this.Close();
            }
        }
        #endregion

        #region 按钮事件
        private void btnDownload_Click(object sender, EventArgs e)
        {
            try
            {
                UpImage.UpFileSoapClient server = new UpImage.UpFileSoapClient();
                DataTable newdt = new DataTable();
                newdt = filelist.Clone(); // 克隆dt 的结构，包括所有 dt 架构和约束,并无数据；
                int index = this.dgrfile.CurrentCell.RowIndex;
                string strWhere = "1>0";
                int cellindex = dgrfile.SelectedCells[0].RowIndex;
                itemsToDown = dgrfile.Rows[index].Cells[0].Value.ToString();
                if (itemsToDown == "" || itemsToDown == null)
                {
                    MessageBox.Show("请在FTP文件浏览器中选择条目！");
                    return;
                }
                strWhere += string.Format(" and FILE_ID = '{0}'", itemsToDown);
                DataRow[] rows = filelist.Select(strWhere); // 从dt 中查询符合条件的记录；
                foreach (DataRow row in rows)  // 将查询的结果添加到dt中；
                {
                    newdt.Rows.Add(row.ItemArray);
                }
                strGIud = newdt.Rows[0]["FILE_ID"].ToString().Substring(0, 36);
                DataSet ds = server.GetfileInfo(strGIud + "-" + branchid.ToString());
                if (ds.Tables[0].Rows.Count > 0)
                {
                    MessageBox.Show("该文件已经存在！");
                    return;
                }
                string strType = newdt.Rows[0]["TYPE"].ToString();
                if (strType == "图片")
                {
                    flag = 0;
                }
                else if (strType == "视频")
                {
                    flag = 1;
                }
                fileName = newdt.Rows[0]["URLOriginal"].ToString();
                branchidfrom = Convert.ToInt32(newdt.Rows[0]["BRANCH_ID"].ToString());
                previousFileName = fileName.Substring(fileName.LastIndexOf("/") + 1).ToString();
                filetitle = newdt.Rows[0]["FILE_TITEL"].ToString();
                strsuffix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();
                newfileName = strGIud + "." + strsuffix;
                ftpdown = new FTPClient(HeadNASIP, "", HeadnasUserName, HeadnasPassword, 21);               
                ftpup = new FTPClient(NASIP, "", NASusername, NASpassword, 21);
                ftpup.ChDir(firstURL);
                if (flag == 1)
                {
                    ftpdown.ChDir(VideoURL);
                    long longsize = ftpdown.GetFileSize(previousFileName);
                    if (longsize == 0)
                    {
                        MessageBox.Show("总店不存在该文件！请确认总店文件是否被错误删除");
                        return;
                    }
                    ftpdown.ChDir(VideoURL);
                    ftpup.ChDir(VideoURL);
                    URL = firstURL + VideoURL;
                    URLVideoPhoto = newdt.Rows[0]["URLThumbnail"].ToString();
                    newVideoImage = URLVideoPhoto.Substring(fileName.LastIndexOf("/") + 1).ToLower();

                }
                else if (flag == 0)
                {
                    ftpdown.ChDir(ImageURL);
                    long longsize = ftpdown.GetFileSize(previousFileName);
                    if (longsize == 0)
                    {
                        MessageBox.Show("总店不存在该文件！请确认总店文件是否被错误删除");
                        return;
                    }
                    ftpdown.ChDir(ImageURL);
                    ftpup.ChDir(ImageURL);
                    URL = firstURL + ImageURL;
                }
                //long longsize = ftpdown.GetFileSize(previousFileName);
                //if (longsize == 0)
                //{
                //    MessageBox.Show("总店不存在该文件！请确认总店文件是否被错误删除");
                //    return;
                //}
                SynchronizationContext uiContext = SynchronizationContext.Current;
                Thread DownThread = new Thread(DownFile);
                Thread UpThread = new Thread(UpFile);
                DownThread.Start(uiContext);
                UpThread.Start(uiContext);
                DownThread.Join();
                UpThread.Join();
                MessageBox.Show("文件下载成功！");
                server.Synchronizaion(strGIud, chek_fileattr.Checked, che_filepro.Checked, branchidfrom, branchid);
                dgrfile.Rows.RemoveAt(cellindex);

            }
            catch (Exception)
            {
                MessageBox.Show("没有文件可以选择！");
                return;
            }
            //finally
            //{
            //    MessageBox.Show("文件下载成功！");
            //    UpImage.UpFileSoapClient server = new UpImage.UpFileSoapClient();
            //    server.Synchronizaion(strGIud, chek_fileattr.Checked, che_filepro.Checked, branchidfrom, branchid);
            //}
        }
        #endregion

        #region 文件下载进程方法
        private void DownFile(object State)
        {
            FTPClient.Flag = 0;
            ftpdown.GetThreadFuc(previousFileName, State, UpdateUI);
        }
        #endregion

        #region 文件上传进程方法
        private void UpFile(object State)
        {
            ftpup.PutThreadFuc(newfileName, State, UpdateUI);
        }
        #endregion

        #region 界面进度条更新
        /// <summary>
        /// This method is executed on the main UI thread.
        /// </summary>
        private void UpdateUI(object state)
        {
            if (state is string)
            {
                this.lbl_tip.Text = state.ToString();
            }
            else
            {
                MessageBox.Show(state.ToString());
            }

        }
        #endregion

        private void btn_return_Click(object sender, EventArgs e)
        {
            FileManage form = new FileManage(userid, username, branchid, NASIP);//通过调用文件管理构造函数传值(用户信息)
            form.Show();
            this.Hide();
        }

        private void Download_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.ExitThread();
        }

        private void dgrfile_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            for (int i = 0; i < dgrfile.Rows.Count; i++)
            {
                int j = i + 1;
                dgrfile.Rows[i].HeaderCell.Value = j.ToString();
            }

        }

        #region 数据绑定
        public void DataBind(DataTable table)
        {
            this.dgrfile.DataSource = table;
            this.dgrfile.Columns[1].HeaderCell.Value = "文件类型";
            int count = table.Rows.Count;
            for (int i = 0; i < count; i++)
            {
                if (table.Rows[i][1].ToString() == "1" || table.Rows[i][1].ToString() == "视频")
                {
                    this.dgrfile.Rows[i].Cells[1].Value = "视频";
                }
                if (table.Rows[i][1].ToString() == "0" || table.Rows[i][1].ToString() == "图片")
                {
                    this.dgrfile.Rows[i].Cells[1].Value = "图片";
                }
            }
            this.dgrfile.Columns[0].Visible = false;
            this.dgrfile.Columns[2].Visible = false;
            this.dgrfile.Columns[3].HeaderCell.Value = "文件主题";
            this.dgrfile.Columns[4].HeaderCell.Value = "上传时间";
            this.dgrfile.Columns[5].HeaderCell.Value = "上传人";
            this.dgrfile.Columns[6].HeaderCell.Value = "是否设置";
            this.dgrfile.Columns[6].ReadOnly = true;
            this.dgrfile.Columns[7].HeaderCell.Value = "上传分店";
            this.dgrfile.Columns[8].HeaderCell.Value = "文件项目备注";
            this.dgrfile.Columns[9].Visible = false;
            this.dgrfile.Columns[10].Visible = false;
            this.dgrfile.Columns[11].Visible = false;
            this.dgrfile.Columns[12].Visible = false;
            this.dgrfile.Columns[13].Visible = false;
            this.dgrfile.Columns[14].Visible = false;
        }
        #endregion

        #region 绑定combox控件
        public void DataCombox()
        {
            ArrayList arrayList1 = new ArrayList();
            ArrayList arrayList2 = new ArrayList();
            arrayList1.Add(new DictionaryEntry(0, ""));
            arrayList2.Add(new DictionaryEntry(0, ""));
            UpImage.UpFileSoapClient server = new UpImage.UpFileSoapClient();
            DataSet Dictinaryds = server.GetDictionary(12);
            for (int i = 0; i < Dictinaryds.Tables[0].Rows.Count; i++)
            {
                arrayList1.Add(new DictionaryEntry(Dictinaryds.Tables[0].Rows[i][0], Dictinaryds.Tables[0].Rows[i][1]));
            }
            cmb_star.DataSource = arrayList1;
            cmb_star.ValueMember = "Key";
            cmb_star.DisplayMember = "Value";
            DataSet Projectds = server.GetProType(0);
            for (int i = 0; i < Projectds.Tables[0].Rows.Count; i++)
            {
                arrayList2.Add(new DictionaryEntry(Projectds.Tables[0].Rows[i][0], Projectds.Tables[0].Rows[i][1]));
            }
            cmb_first.DataSource = arrayList2;
            cmb_first.ValueMember = "Key";
            cmb_first.DisplayMember = "Value";
        }
        #endregion

        #region 格式绑定
        public void FormBing()
        {
            //this.dti_startTimeFrom.Value = DateTime.Now.AddDays(1 - DateTime.Now.Day);//月初
            //this.dti_startTimeTo.Value = DateTime.Now.AddMonths(1).AddDays(1 - DateTime.Now.Day);  //月末
            if (dti_startTimeFrom.Value.ToString() == "")
            {
                this.dti_startTimeFrom.Value = DateTime.Now.AddDays(1 - DateTime.Now.Day);//月初
            }
            if (dti_startTimeTo.Value.ToString() == "")
            {
                this.dti_startTimeTo.Value = DateTime.Now.AddMonths(1).AddDays(1 - DateTime.Now.Day);  //月末
            }
            this.dgrfile.ColumnHeadersDefaultCellStyle.Font = new Font("宋体", 10, FontStyle.Bold, GraphicsUnit.Point);
            this.dgrfile.ColumnHeadersDefaultCellStyle.BackColor = SystemColors.GradientInactiveCaption;
            this.dgrfile.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.dgrfile.DefaultCellStyle.Font = new Font("宋体", 9, FontStyle.Regular, GraphicsUnit.Point);
            this.dgrfile.DefaultCellStyle.BackColor = Color.Empty;

        }

        #endregion

        #region 绑定UserPageTool控件
        public void UserPageToolBind(DataTable table)
        {
            this.userPageTool1.Dgv = this.dgrfile;
            this.userPageTool1.Dt = table;
            this.userPageTool1.InitDataSet(8);
            if (table.Rows.Count > 0)
            {
                this.dgrfile.CurrentCell = this.dgrfile.Rows[0].Cells[1];
            }
            FormBing();
        }
        #endregion

        private void btn_search_Click(object sender, EventArgs e)
        {
            string TimeFrom;
            string TimeTo;
            string FileTitle;
            string FileUserName;
            string FileBranchName;
            int indexStar;
            int indexProjecttype;
            if (dti_startTimeFrom.Value.ToString() == "")
            {
                this.dti_startTimeFrom.Value = DateTime.Now.AddMonths(-1);
            }
            if (dti_startTimeTo.Value.ToString() == "")
            {
                this.dti_startTimeTo.Value = DateTime.Now;
            }
            TimeFrom = dti_startTimeFrom.Text + " " + "00:00:00 ";
            TimeTo = dti_startTimeTo.Text + " " + "23:59:59 ";
            if (txt_title.Text.ToString() != null)
            {
                FileTitle = txt_title.Text.ToString();
            }
            else
            {
                FileTitle = "";
            }
            if (txb_user.Text.ToString() != null)
            {
                FileUserName = txb_user.Text.ToString();
            }
            else
            {
                FileUserName = "";
            }
            if (txt_branch.Text.ToString() != null)
            {
                FileBranchName = txt_branch.Text.ToString();
            }
            else
            {
                FileBranchName = "";
            }
            if (cmb_star.SelectedIndex != -1)
            {
                indexStar = cmb_star.SelectedIndex;
            }
            else
            {
                indexStar = 0;
            }
            if (cmb_first.SelectedIndex != -1 && cmb_second.SelectedIndex != -1)
            {
                indexProjecttype = cmb_second.SelectedIndex;
            }
            else
            {
                indexProjecttype = 0;
            }
            string strWhere = "1>0";
            if (FileTitle != "")
            {
                strWhere += string.Format(" and FILE_TITEL like '%{0}%'", FileTitle);
            }
            if (FileUserName != "")
            {
                strWhere += string.Format(" and USERNAME like '%{0}%'", FileUserName);
            }
            if (FileBranchName != "")
            {
                strWhere += string.Format(" and BRANCH_NAME like '%{0}%'", FileBranchName);
            }
            if (indexStar !=0)
            {
                strWhere += string.Format(" and MATERIAL_STAR = '{0}'", indexStar);
            }
            if (indexProjecttype !=0)
            {
                strWhere += string.Format(" and PROJECT_TYPE = '{0}'", indexProjecttype);
            }
            DataTable newdt = new DataTable();
            newdt = filelist.Clone(); // 克隆dt 的结构，包括所有 dt 架构和约束,并无数据；
            strWhere += string.Format(" and UPTIME>'{0}' and UPTIME<'{1}'", TimeFrom, TimeTo);
            if (filelist.Rows.Count != 0)
            {
                DataRow[] rows = filelist.Select(strWhere); // 从dt 中查询符合条件的记录；
                foreach (DataRow row in rows)  // 将查询的结果添加到dt中；
                {
                    newdt.Rows.Add(row.ItemArray);
                }
                UserPageToolBind(newdt);
                DataBind(newdt);
            }
        }

        private void cmb_first_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpImage.UpFileSoapClient server = new UpImage.UpFileSoapClient();
            ArrayList arrayList3 = new ArrayList();
            arrayList3.Add(new DictionaryEntry(0, ""));
            DataSet ProjectdsSecond = server.GetProType(cmb_first.SelectedIndex);
            for (int i = 0; i < ProjectdsSecond.Tables[0].Rows.Count; i++)
            {
                arrayList3.Add(new DictionaryEntry(ProjectdsSecond.Tables[0].Rows[i][0], ProjectdsSecond.Tables[0].Rows[i][1]));
            }
            cmb_second.DataSource = arrayList3;
            cmb_second.ValueMember = "Key";
            cmb_second.DisplayMember = "Value";
        }

        private void dgrfile_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int index = e.RowIndex;
            string strUrl = this.dgrfile.Rows[index].Cells[10].Value.ToString();
            string strName = this.dgrfile.Rows[index].Cells[2].Value.ToString();
            string strType = this.dgrfile.Rows[index].Cells[1].Value.ToString();
            if (ishead)
            {
                strUrl = "ftp://" + HeadNASIP + "/" + strUrl;
            }
            else
            {
                strUrl = "ftp://" + NASIP + "/" + strUrl;
            }
            if (strType == "0" || strType == "图片")
            {
                ShowPhoto form = new ShowPhoto(strUrl, strName);//通过调用文件下载构造函数传值(用户信息)
                form.Show();
            }
            if (strType == "1" || strType == "视频")
            {
                PlayVdio form = new PlayVdio(strUrl, strName);//通过调用文件下载构造函数传值(用户信息)
                form.Show();
            }
        }

        private void btn_exit_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
        }
    }
}
